@extends('seller::layout.master')

@section('title', __('seller::shipping.title'))

@section('content')
  <div id="shipping-app" class="card">
    <div class="card-header">{{ __('seller::shipping.title') }}</div>
    <div class="card-body">
      <form class="needs-validation" novalidate action="{{ seller_route($shipping->id ? 'shipping.update' : 'shipping.store', $shipping) }}"
        method="POST" id="rules-app">
        @csrf
        @method($shipping->id ? 'PUT' : 'POST')
        <input type="text" class="d-none" name="_redirect" value="{{ $_redirect }}">

        <x-seller::form.row title="{{ __('seller::shipping.text_region') }}">
          <div class="input-group w-max-400">
            <select class="form-select" name="region_id">
              @foreach ($regions as $item)
                <option value="{{ $item->id }}"{{ $item->id == $shipping->region_id ? 'selected' : '' }}>{{ $item->name }}</option>
              @endforeach
            </select>
          </div>
        </x-seller::form.row>

        <x-seller::form.row title="{{ __('seller::shipping.text_type') }}">
          <div class="input-group w-max-400">
            <select class="form-select" name="type" @change="typeChange">
              <option value="by_flat" {{ $shipping->type == 'by_flat' ? 'selected' : '' }}>{{ __('seller::shipping.by_flat') }}</option>
              <option value="by_weight" {{ $shipping->type == 'by_weight' ? 'selected' : '' }}>{{ __('seller::shipping.by_weight') }}</option>
            </select>
          </div>
        </x-seller::form.row>

        <div v-show="form.type == 'by_weight'">
          <x-seller::form.row title="{{ __('seller::shipping.text_method') }}">
            <div class="input-group w-max-400">
              <select class="form-select" name="method">
                <option value="range" {{ $shipping->method == 'range' ? 'selected' : '' }}>{{ __('seller::shipping.text_range') }}</option>
                <option value="cumulative" {{ $shipping->method == 'cumulative' ? 'selected' : '' }}>{{ __('seller::shipping.text_cumulative') }}</option>
              </select>
            </div>
          </x-seller::form.row>
        </div>

        <div v-show="form.type == 'by_weight'">
          <x-seller::form.row title="{{ __('seller::shipping.text_rules') }}">
            <div class="input-group w-max-800 table-push">
              <input type="hidden" :value="rulesJson" name="rules" />
              <el-form :model="form" ref="formxssss" label-width="100px" class="w-100">
                <table class="table table-bordered w-100">
                  <thead>
                    <tr>
                      <th>{{ __('seller::shipping.text_rules_start') }}({{ default_weight_class() }})</th>
                      <th>{{ __('seller::shipping.text_rules_end') }} ({{ default_weight_class() }})</th>
                      <th>{{ __('seller::shipping.text_rules_cost') }}</th>
                      <th>{{ __('seller::shipping.text_rules_block') }} ({{ default_weight_class() }})</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="rule, index in form.rules" :key="index">
                      <td class="pb-4">
                        <el-form-item
                          :prop="'rules.' + index + '.start'"
                          label-width="0"
                          class="mb-0"
                          :rules="rules.start"
                        >
                          <el-input v-model="rule.start" size="small"><template slot="prepend">></template></el-input>
                        </el-form-item>
                      </td>
                      <td class="pb-4">
                        <el-form-item
                          :prop="'rules.' + index + '.end'"
                          label-width="0"
                          class="mb-0"
                          :rules="rules.end"
                        >
                          <el-input v-model="rule.end" size="small"><template slot="prepend"><=</template></el-input>
                        </el-form-item>
                      </td>
                      <td class="pb-4">
                        <el-form-item
                          :prop="'rules.' + index + '.cost'"
                          label-width="0"
                          class="mb-0"
                          :rules="[
                            { required: true, message: '{{ __('seller::shipping.err_cost_null') }}', trigger: ['change', 'blur'] },
                          ]"
                        >
                          <el-input v-model="rule.cost" size="small"><template slot="prepend">{{ current_currency_code() }}</template></el-input>
                        </el-form-item>
                      </td>
                      <td class="pb-4">
                        <el-form-item
                          :prop="'rules.' + index + '.block'"
                          label-width="0"
                          class="mb-0"
                          :rules="[
                            { required: true, message: '{{ __('seller::shipping.err_block_null') }}', trigger: ['change', 'blur'] },
                          ]"
                        >
                          <el-input v-model="rule.block" size="small"></el-input>
                        </el-form-item>
                      </td>
                      <td class="pb-4">
                        <button type="button" class="btn btn-outline-danger btn-sm text-nowrap" @click="form.rules.splice(index, 1)">{{ __('common.delete') }}</button>
                      </td>
                    </tr>
                  </tbody>
                  <tfoot>
                    <tr>
                      <td colspan="5" class="text-end">
                        <button type="button" class="btn btn-outline-secondary btn-sm" @click="addRules">{{ __('seller::shipping.text_rules_add') }}</button>
                      </td>
                    </tr>
                  </tfoot>
                </table>
              </el-form>
            </div>
          </x-seller::form.row>
        </div>

        <x-seller-form-input name="flat" :error="$errors->first('flat')" :title="__('seller::shipping.text_flat')" :value="old('flat', $shipping->flat ?? '')" />

        <x-seller-form-input name="priority" :error="$errors->first('priority')" :title="__('seller::shipping.text_priority')" :value="old('priority', $shipping->priority ?? '')" />

        <x-seller-form-switch title="{{ __('common.status') }}" name="status" :value="old('status', $shipping->status ?? 1)" />

        <x-seller::form.row>
          <button type="button" class="btn btn-primary mt-3" @click="formSubmit">{{ __('common.save') }}</button>
        </x-seller::form.row>
      </form>
    </div>
  </div>
@endsection

@push('footer')
<script>
  $(function() {
    $('input[name="flat"]').keyup(function() {
      $(this).val($(this).val().replace(/[^(\d|.)]/g, ''));

      // 只有一个点 则清空
      if ($(this).val() == '.') {
        $(this).val('');
      }
    });

    $('input[name="priority"]').keyup(function() {
      $(this).val($(this).val().replace(/[^\d]/g, ''));
    });
  })

  let validatorStart = (rule, value, callback) => {
    let index =  rule.fullField.split('.')[1];

    // 不能为空
    if (!value) {
      callback(new Error('{{ __('seller::shipping.err_start_null') }}'));
    }

    // 判断开始值不能小于上一条的结束值
    if (index > 0) {
      let prev = app.form.rules[index - 1];
      if (value * 1 < prev.end * 1) {
        callback(new Error('{{ __('seller::shipping.err_start_val') }}'));
      }
    }

    callback();
  };

  let validatorEnd = (rule, value, callback) => {
    let index =  rule.fullField.split('.')[1];
    let start = app.form.rules[index].start * 1;

    // 不能为空
    if (!value) {
      callback(new Error('{{ __('seller::shipping.err_end_null') }}'));
    }

    // 判断结束值不能小于开始值
    if (value * 1 <= start) {
      callback(new Error('{{ __('seller::shipping.err_end_val') }}'));
    }

    callback();
  };

  let app = new Vue({
    el: '#rules-app',

    data: {
      form: {
        rules: @json(old('rules', json_decode($shipping->rules ?? '[]', true))),
        type: @json(old('type', $shipping->type ?? '')),
      },

      rules: {
        start: [{validator: validatorStart, trigger: ['change', 'blur']}],
        end: [{validator: validatorEnd, trigger: ['change', 'blur']}],
      }
    },

    // 计算属性
    computed: {
      rulesJson() {
        return JSON.stringify(this.form.rules);
      }
    },

    methods: {
      addRules() {
        this.form.rules.push({
          start: '',
          end: '',
          cost: '',
          block: ''
        })
      },

      formSubmit() {
        if (this.form.type == 'by_weight') {
          if (!this.form.rules.length) {
            layer.msg('请添加计算规则', ()=>{})
            return;
          }

          this.$refs['formxssss'].validate((valid) => {
            if (valid) {
              $('#rules-app').submit();
            }
          })
        } else {
          $('#rules-app').submit();
        }
      },

      typeChange(e) {
        let value = e.target.value;
        this.form.type = value;
      }
    }
  })
</script>

<style>
  .mb-0 .el-form-item__content {
    line-height: 1;
  }

  @media (max-width: 768px) {
    .el-input-group__prepend {
      padding: 0 8px;
    }

    .el-form .el-form-item .el-input__inner {
      min-width: 70px;
      padding: 0 10px;
    }
  }
</style>
@endpush